<template>
  <div class="chart-container" style="width: 100%; height: 21vh">
    <div ref="chart" class="chart" style="width: 100%; height: 100%"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

// 创建响应式引用
const chart = ref<HTMLDivElement | null>(null)
let myChart: echarts.ECharts | null = null

// 初始化图表
const initChart = () => {
  if (chart.value) {
    myChart = echarts.init(chart.value)
    setChartOptions()
  }
}

// 设置图表选项
const setChartOptions = () => {
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        show: false
      },
      axisLine: {
        show: false
      },
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'category',
      data: ['生产车间', '注塑车间', '组装车间', '测试车间'],
      axisTick: {
        show: false
      },
      axisLine: {
        show: false
      }
    },
    grid: {
      left: '70px',
      right: '5px',
      top: '5px',
      bottom: '5px'
    },
    series: [
      {
        data: [650, 390, 374, 222],
        type: 'bar',
        label: {
          show: true,
          position: 'right',
          formatter: '{c} 件'
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#56E6A6' },
            { offset: 1, color: '#3798E3' }
          ])
        }
      }
    ]
  }
  if (myChart) {
    myChart.setOption(option)
  }
}

// 处理窗口大小调整
const handleResize = () => {
  if (myChart) {
    myChart.resize()
  }
}

// 生命周期钩子
onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.chart-container {
  display: flex;
  width: 100%; /* 容器宽度占据父容器的 100% */
  height: 20vh;
}

.chart {
  width: 100%; /* 图表宽度根据容器自动调整 */
  height: 100%; /* 图表高度根据容器自动调整 */
}
</style>
